const permissionsModel = require("../../model/permissions");
const roleModel = require("../../model/role");
const { flatToTree } = require("../../utils/treeHandle");
const mongoose = require("mongoose");

// 获取所有权限
exports.getPermissions = async (req, res) => {
	const query = {};
	if (req.query.permission_name) query.permission_name = new RegExp(req.query.permission_name, "i");
	if (req.query.status) query.status = req.query.status;

	try {
		const permissionRes = await permissionsModel.find(query).lean();
		const permissionTree = flatToTree({ dataArr: permissionRes });

		res.json({ code: 200, msg: "获取权限列表成功", data: permissionTree });
	} catch (error) {
		res.json({ code: 500, msg: "获取权限列表失败" });
	}
};

// 创建权限
exports.createPermission = async (req, res, next) => {
	// 兼容前端
	if (req.body.pid === "root") delete req.body.pid;

	try {
		const ret = await permissionsModel.create(req.body);
		res.json({ code: 200, msg: "权限创建成功", data: ret });
	} catch (error) {
		console.log(error);
		res.json({ code: 500, msg: "权限创建失败" });
	}
};

// 更新权限
exports.updatePermission = async (req, res) => {
	// 查询当前权限信息
	const permissionInfo = await permissionsModel.findOne({ _id: req.body._id });
	if (req.body.pid === "root") delete req.body.pid;

	// 如果状态变化了则需要更新子节点 | 如果有pid则需要判断pid是否为它的子节点
	let subordinates = [];
	if (req.body.status !== permissionInfo.status || req.body.pid) {
		subordinates = await permissionsModel.aggregate([
			{
				$match: { _id: new mongoose.Types.ObjectId(req.body._id) },
			},
			{
				$graphLookup: {
					from: "permissions",
					startWith: "$_id",
					connectFromField: "_id",
					connectToField: "pid",
					as: "children",
				},
			},
		]);
		if (subordinates.length > 0) subordinates = subordinates[0].children;
	}

	// 状态变化了, 则需要更新子节点
	if (req.body.status !== permissionInfo.status) {
		await permissionsModel.updateMany({ _id: { $in: subordinates.map((item) => item._id) } }, { status: req.body.status });

		// 查询父级的状态是否为禁用
		const parentInfo = await permissionsModel.findOne({ _id: permissionInfo.pid });
		if (parentInfo.status === "disable") return res.json({ code: 500, msg: "父级状态为禁用, 无法修改~" });
	}

	// 如果有pid则需要校验
	if (req.body.pid) {
		if (req.body._id === req.body.pid) return res.json({ code: 500, msg: "自己不能插入自己~" });

		const subIds = subordinates.map((item) => item._id.toString());
		if (subIds.includes(req.body.pid)) return res.json({ code: 500, msg: "不能插入自己的子节点~" });
	} else {
		// 如果没有则删除pid, 将它值为顶级.
		req.body = { ...req.body, ...{ $unset: { pid: 1 } } };
	}

	try {
		const ret = await permissionsModel.updateOne({ _id: req.body._id }, req.body);
		res.json({ code: 200, msg: "权限更新成功", data: ret });
	} catch (error) {
		console.log(error.message);
		res.json({ code: 500, msg: "权限更新失败" });
	}
};

// 删除权限
exports.deletePermission = async (req, res) => {
	let subordinates = [];
	try {
		subordinates = await permissionsModel.aggregate([
			{
				$match: { _id: new mongoose.Types.ObjectId(req.body.id) },
			},
			{
				$graphLookup: {
					from: "permissions",
					startWith: "$_id",
					connectFromField: "_id",
					connectToField: "pid",
					as: "children",
				},
			},
		]);
		if (subordinates.length > 0) subordinates = subordinates[0].children.map((item) => item._id.toString());
	} catch (e) {
		return res.json({ code: 500, msg: "权限删除失败" });
	}

	try {
		// 从角色表中删除这些权限数据
		await roleModel.updateMany(
			{
				permissions: { $in: [req.body.id, ...subordinates] },
			},
			{
				$pull: {
					permissions: { $in: [req.body.id, ...subordinates] },
				},
			}
		);

		const ret = await permissionsModel.deleteMany({ _id: { $in: [...subordinates, req.body.id] } });
		res.json({ code: 200, msg: "权限删除成功", data: ret });
	} catch (error) {
		console.log(error);
		res.json({ code: 500, msg: "权限删除失败" });
	}
};
